import datasource
from datasource import TaskType
import json
import threading
import time
from flask import Flask, request, jsonify
#from m import mystage,curMatchIndex, curStageID, curMatchID, curUUID, matchuuidlist, singleMatchDatas, RefreshStages
import m

app = Flask(__name__)
matchmap = {0:"龙隐洞天", 1:"火罗国",2:"聚窟洲",3:"龙隐洞天",4:"火罗国",5:"聚窟洲",6:"龙隐洞天",7:"火罗国",8:"聚窟洲",9:"-",10:"-"}
heartdata = None

DEBUG = False

def runapp():
    global app
    app.run(host='0.0.0.0', port=18902)

@app.route('/SendData', methods=['POST'])
def RecvData():
    global heartdata
    text = request.json.get('data')
    if not text or text == "":
        return jsonify({'error': 'No data provided'}), 400
    # 发送文本到TTS处理端
    heartdata = text
    print(f"收到了 {text}")
    return jsonify({'msg': 'success'}), 200

@app.route('/GetData')
def GetHeartData():
    global heartdata
    if heartdata is not None:
        #return res, 200
        return heartdata, 200
    else:
        tmp = [{"heartRate":0,"nickname":"-","userid":10000000,"time":10000000},{"heartRate":0,"nickname":"-","userid":10000000,"time":10000000}]
        jsonstr = json.dumps(tmp, ensure_ascii=False, indent=4)
        return jsonstr,200

@app.route('/HeroSelect')
def HttpHeroSelectTeam():
    if m.isSingle:
        ee = CapHeroSelectSingle()
    else:
        ee = CapHeroSelectTeam()
    if ee is not None:
        #return res, 200
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409
    
@app.route('/BornPosition')
def HttpBornPosition():
    ee = CapBornPos()
    if ee is not None:
        #return res, 200
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409
    
@app.route('/SingleScore')
def HttpSingleScore():
    ee = CapSingleScore()
    if ee is not None:
        #return res, 200
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409  
    
@app.route('/TotalScore')
def HttpTotalScore():
    ee = CapTotalScore()
    if ee is not None:
        #return res, 200
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409     
    
@app.route('/MatchEndData')
def HttpMatchEndData():
    ee = CapMatchEndData()
    if ee is not None:
        #return res, 200
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409    
    
@app.route('/Top10')
def HttpTop10():
    ee = CapTop10()
    if ee is not None:
        #return res, 200
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409  
    
@app.route('/AvgScore')
def HttpAvgScore():
    ee = CapAvgScore()
    if ee is not None:
        #return res, 200
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409   
    
@app.route('/AllMatchScore')
def HttpAllMatchScore():
    ee = CapAllMatchScore()
    if ee is not None:
        #return res, 200
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409   
    
@app.route('/RealtimeLive')
def HttpRealtimeLive():
    ee = CapRealtimeLive()
    if ee is not None:
        #return res, 200
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409  
    
@app.route('/Mvp')
def HttpMvp():
    ee = CapMvp()
    if ee is not None:
        #return res, 200
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409  
    
@app.route('/Event')
def HttpEvent():
    ee = CapRealtimeEvent()
    if ee is not None:
        #return res, 200
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409     

@app.route('/OuterWeb')
def HttpOuterWeb():
    ee = CapOuterWeb()
    if ee is not None:
        #return res, 200
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409
    
@app.route('/SetMatch')
def SetMatch():
    # 获取 GET 请求中的参数
    param1 = request.args.get('Number', 1)  # 获取名为 'param1' 的参数
    m.SetCurMatch(int(param1))
    return f"Received param1: {param1}"

@app.route('/GetMatch')
def GetMatch():
    ee = m.GetMatch()
    if ee is not None:
        return ee, 200
    else:
        return jsonify({'error': '？'}), 409  


# 英雄选择3排，计算
def CapHeroSelectTeam():
    global DEBUG
    global matchmap
    posdata = datasource.GetPosAndHero(m.curStageID)
    teamlist = []  #队伍列表
    if posdata ==None:
        retjson = {"data":[]}
        jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
        return jsonstr
    if posdata != None:
        #matchround = posdata["data"]["match_round"]
        mymap = posdata["data"]["map"]
        # matchmap[m.curMatchIndex] = mymap   反正是比赛定死的，就不去读取了
        if "team" in posdata["data"] and isinstance(posdata["data"]["team"],list):
            if len(posdata["data"]["team"]) > 0:
                for iteam in posdata["data"]["team"]:
                    player1=["-",0,"-","-"]
                    player2=["-",0,"-","-"]
                    player3=["-",0,"-","-"]
                    if len(iteam["role_info"]) >= 1:
                        player1 = [iteam["role_info"][0]["role_name"],iteam["role_info"][0]["hero_id"],iteam["role_info"][0]["skills"][0]["skill_name"],iteam["role_info"][0]["skills"][1]["skill_name"]]
                    if len(iteam["role_info"]) >= 2:
                        player2 = [iteam["role_info"][1]["role_name"],iteam["role_info"][1]["hero_id"],iteam["role_info"][1]["skills"][0]["skill_name"],iteam["role_info"][1]["skills"][1]["skill_name"]]
                    if len(iteam["role_info"]) >= 3:
                        player3 = [iteam["role_info"][2]["role_name"],iteam["role_info"][2]["hero_id"],iteam["role_info"][2]["skills"][0]["skill_name"],iteam["role_info"][2]["skills"][1]["skill_name"]]
                    tmpteam = {
                        "team_name":iteam["team_name"],
                        "players":[
                            {
                                "player_name": player1[0],
                                "hero_id": m.convertList.get(str(player1[1]),"-"),
                                "skillF":player1[2],
                                "skillV":player1[3],
                                "mid":player1[1]
                            },
                            {
                                "player_name": player2[0],
                                "hero_id": m.convertList.get(str(player2[1]),"-"),
                                "skillF":player2[2],
                                "skillV":player2[3],
                                "mid":player2[1]
                            },
                            {
                                "player_name": player3[0],
                                "hero_id": m.convertList.get(str(player3[1]),"-"),
                                "skillF":player3[2],
                                "skillV":player3[3],
                                "mid":player3[1]
                            }
                        ],
                        "pick_rate":"-",
                        "average_score":"-",
                        "last_score":"-"
                    }
                    teamlist.append(tmpteam)  #添加进来
    #好，选手填完了，接下来去填充选择率和积分的数据
    lineupdata = datasource.GetHeroLineup(m.curUUID,m.curStageID)
    if lineupdata!=None:
        if lineupdata["data"]!=None and len(lineupdata["data"]) > 0:
            for itemmy in teamlist:
                for index, itemhe in enumerate(lineupdata["data"]):
                    if itemhe["team_name"] == itemmy["team_name"]:
                        myheros = [itemmy["players"][0]["mid"],itemmy["players"][1]["mid"],itemmy["players"][2]["mid"]]
                        myheross = sorted(myheros)
                        if myheross == itemhe["hero_id"]:
                            itemmy["pick_rate"] = itemhe["pick_rate"]
                            itemmy["average_score"] = itemhe["average_score"]
    #好，接下来是上局积分，不好填了呀这个
    if m.curMatchIndex > 0:  #不是第一场
        #第一局，就不用去查上局积分了，只有不是第一局的时候才去查
        for itemmy in teamlist:
            if m.singleMatchDatas[m.curMatchIndex-1] != []:
                for index, itemhe in enumerate(m.singleMatchDatas[m.curMatchIndex-1]):
                    if itemhe["team_name"] == itemmy["team_name"]:
                        itemmy["last_score"] = itemhe["score"]
    #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":teamlist,"map":mymap}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr

# 英雄选择单排，计算
def CapHeroSelectSingle():
    global DEBUG
    posdata = datasource.GetPosAndHero(m.curStageID) #不用换，变了阶段就变成单人了
    if posdata ==None:
        retjson = {"data":[]}
        jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
        return jsonstr
    teamlist = []  #队伍列表
    if posdata != None:
        #matchround = posdata["data"]["match_round"]
        mymap = posdata["data"]["map"]
        if "team" in posdata["data"] and isinstance(posdata["data"]["team"],list):
            if len(posdata["data"]["team"]) > 0:
                for iteam in posdata["data"]["team"]:
                    player1=["-",0,"-","-"]
                    player2=["-",0,"-","-"]
                    player3=["-",0,"-","-"]
                    if len(iteam["role_info"]) >= 1:
                        player1 = [iteam["role_info"][0]["role_name"],iteam["role_info"][0]["hero_id"],iteam["role_info"][0]["skills"][0]["skill_name"],iteam["role_info"][0]["skills"][1]["skill_name"]]
                    if len(iteam["role_info"]) >= 2:
                        player2 = [iteam["role_info"][1]["role_name"],iteam["role_info"][1]["hero_id"],iteam["role_info"][1]["skills"][0]["skill_name"],iteam["role_info"][1]["skills"][1]["skill_name"]]
                    if len(iteam["role_info"]) >= 3:
                        player3 = [iteam["role_info"][2]["role_name"],iteam["role_info"][2]["hero_id"],iteam["role_info"][2]["skills"][0]["skill_name"],iteam["role_info"][2]["skills"][1]["skill_name"]]
                    tmpteam = {
                        "team_name":iteam["team_name"],
                        "players":[
                            {
                                "player_name": player1[0],
                                "hero_id": m.convertList.get(str(player1[1]),"-"),
                                "skillF":player1[2],
                                "skillV":player1[3],
                                "mid":player1[1]
                            },
                            {
                                "player_name": player2[0],
                                "hero_id": m.convertList.get(str(player2[1]),"-"),
                                "skillF":player2[2],
                                "skillV":player2[3],
                                "mid":player2[1]
                            },
                            {
                                "player_name": player3[0],
                                "hero_id": m.convertList.get(str(player3[1]),"-"),
                                "skillF":player3[2],
                                "skillV":player3[3],
                                "mid":player3[1]
                            }
                        ],
                        "pick_rate":"-",
                        "average_score":"-",
                        "last_score":"-"
                    }
                    teamlist.append(tmpteam)  #添加进来
    #好，选手填完了，接下来去填充选择率和积分的数据
    lineupdata = datasource.GetHeroLineup(m.curUUID,m.curStageID)
    if lineupdata!=None:
        if lineupdata["data"]!=None and len(lineupdata["data"]) > 0:
            for itemmy in teamlist:
                for index, itemhe in enumerate(lineupdata["data"]):
                    if itemhe["role_name"] == itemmy["players"][0]["player_name"] and itemhe["hero_id"] == itemmy["players"][0]["mid"]:
                        itemmy["pick_rate"] = itemhe["pick_rate"]
                        itemmy["average_score"] = itemhe["average_score"]
     #好，接下来是上局积分，不好填了呀这个
    if m.curMatchIndex > 0:  #不是第一场
        #第一局，就不用去查上局积分了，只有不是第一局的时候才去查
        for itemmy in teamlist:
            if m.singleMatchDatas[m.curMatchIndex-1] != []:
                for index, itemhe in enumerate(m.singleMatchDatas[m.curMatchIndex-1]):
                    if itemhe["team_name"] == itemmy["team_name"]:
                        itemmy["last_score"] = itemhe["score"]
    #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":teamlist,"map":mymap}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr

# 跳点坐标，计算
def CapBornPos():
    global DEBUG
    posdata = datasource.GetPosAndHero(m.curStageID) # 跳点信息在这个接口里面
    if posdata ==None:
        retjson = {"data":[]}
        jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
        return jsonstr
    teamlist = []  #队伍列表
    if posdata!=None:
        matchround = posdata["data"]["match_round"]
        mymap = posdata["data"]["map"]
        if "team" in posdata["data"] and isinstance(posdata["data"]["team"],list):
            if len(posdata["data"]["team"]) > 0:
                for iteam in posdata["data"]["team"]:
                    player1=["-",[0,0,0]]
                    player2=["-",[0,0,0]]
                    player3=["-",[0,0,0]]
                    if len(iteam["role_info"]) >= 1:
                        player1[0] = iteam["role_info"][0]["role_name"]
                        if len(iteam["role_info"][0]["born_postion"]) >= 3:
                            player1[1] = [iteam["role_info"][0]["born_postion"][0],iteam["role_info"][0]["born_postion"][1],iteam["role_info"][0]["born_postion"][2]]
                        # if len(iteam["role_info"][0]["born_postion"]) >= 3:
                        #     player1 = [iteam["role_info"][0]["role_name"],[iteam["role_info"][0]["born_postion"][0],iteam["role_info"][0]["born_postion"][1],iteam["role_info"][0]["born_postion"][2]]]
                    if len(iteam["role_info"]) >= 2:
                        player2[0] = iteam["role_info"][1]["role_name"]
                        if len(iteam["role_info"][1]["born_postion"]) >= 3:
                            player2[1] = [iteam["role_info"][1]["born_postion"][0],iteam["role_info"][1]["born_postion"][1],iteam["role_info"][1]["born_postion"][2]]
                        # if len(iteam["role_info"][1]["born_postion"]) >= 3:
                        #     player2 = [iteam["role_info"][1]["role_name"],[iteam["role_info"][1]["born_postion"][0],iteam["role_info"][1]["born_postion"][1],iteam["role_info"][1]["born_postion"][2]]]
                    if len(iteam["role_info"]) >= 3:
                        player3[0] = iteam["role_info"][2]["role_name"]
                        if len(iteam["role_info"][2]["born_postion"]) >= 3:
                            player3[1] = [iteam["role_info"][2]["born_postion"][0],iteam["role_info"][2]["born_postion"][1],iteam["role_info"][2]["born_postion"][2]]
                        # if len(iteam["role_info"][2]["born_postion"]) >= 3:
                        #     player3 = [iteam["role_info"][2]["role_name"],[iteam["role_info"][2]["born_postion"][0],iteam["role_info"][2]["born_postion"][1],iteam["role_info"][2]["born_postion"][2]]]
                    tmpteam = {
                        "team_name":iteam["team_name"],
                        "players":[
                            {
                                "player_name": player1[0],
                                "born_postion": {
                                    "x":player1[1][0],
                                    "y":player1[1][1],
                                    "z":player1[1][2],
                                }
                            },
                            {
                                "player_name": player2[0],
                                "born_postion": {
                                    "x":player2[1][0],
                                    "y":player2[1][1],
                                    "z":player2[1][2],
                                }
                            },
                            {
                                "player_name": player3[0],
                                "born_postion": {
                                    "x":player3[1][0],
                                    "y":player3[1][1],
                                    "z":player3[1][2],
                                }
                            }
                        ]
                    }
                    teamlist.append(tmpteam)  #添加进来
    #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":teamlist,"map":mymap}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr

# 单局积分，计算
def CapSingleScore():
    global DEBUG
    global matchmap
    scoredata = datasource.GetSingleData(m.curMatchID)
    if scoredata ==None:
        retjson = {"data":[],"map":"-"}
        jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
        return jsonstr
    teamlist = []  #队伍列表
    if scoredata!=None:
        if "teams" in scoredata["data"] and isinstance(scoredata["data"]["teams"],list):
            if len(scoredata["data"]["teams"]) > 0:
                for iteam in scoredata["data"]["teams"]:
                    player1=["-","-","-"]
                    player2=["-","-","-"]
                    player3=["-","-","-"]
                    if len(iteam["players"]) >= 1:
                        player1[0] = iteam["players"][0]["player_game_name"]
                        player1[1] = m.convertList.get(str(iteam["players"][0]["talent_skill_tid"][0]),str(iteam["players"][0]["talent_skill_tid"][0]))
                        player1[2] = m.convertList.get(str(iteam["players"][0]["talent_skill_tid"][1]),str(iteam["players"][0]["talent_skill_tid"][1]))
                    if len(iteam["players"]) >= 2:
                        player2[0] = iteam["players"][1]["player_game_name"]
                        player2[1] = m.convertList.get(str(iteam["players"][1]["talent_skill_tid"][0]),str(iteam["players"][1]["talent_skill_tid"][0]))
                        player2[2] = m.convertList.get(str(iteam["players"][1]["talent_skill_tid"][1]),str(iteam["players"][1]["talent_skill_tid"][1]))
                    if len(iteam["players"]) >= 3:
                        player3[0] = iteam["players"][2]["player_game_name"]
                        player3[1] = m.convertList.get(str(iteam["players"][2]["talent_skill_tid"][0]),str(iteam["players"][2]["talent_skill_tid"][0]))
                        player3[2] = m.convertList.get(str(iteam["players"][2]["talent_skill_tid"][1]),str(iteam["players"][2]["talent_skill_tid"][1]))
                    tmpteam = {
                        "rank":iteam["rank"],
                        "srv_rank":iteam["srv_rank"],
                        "team_name":iteam["team_name"],
                        "players":[
                            {
                                "player_name": player1[0],
                                "skill1":player1[1],
                                "skill2":player1[2]
                            },
                            {
                                "player_name": player2[0],
                                "skill1":player2[1],
                                "skill2":player2[2]
                            },
                            {
                                "player_name": player3[0],
                                "skill1":player3[1],
                                "skill2":player3[2]
                            }
                        ],
                        "kill_times":iteam["kill_times"],
                        "kill_score":iteam["kill_score"],
                        "rank_score":iteam["rank_score"],
                        "score":iteam["score"]
                    }
                    teamlist.append(tmpteam)  #添加进来
    #开始计算
    sorted_data = sorted(teamlist, key=lambda x: x['rank'], reverse=False)
    # # 更新 rank 字段
    # for rank, player in enumerate(sorted_data):
    #     player['rank'] = rank + 1  # rank 从 1 开始       
    #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":sorted_data,"map":matchmap[m.curMatchIndex]}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr

# 总积分，计算
def CapTotalScore():
    global DEBUG
    totalscore = datasource.GetRealtimeScore(m.curStageID,0)
    if totalscore ==None:
        retjson = {"data":[],"matchPointScore":0}
        jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
        return jsonstr
    teamlist = []  #队伍列表
    #scoredata = datasource.GetSingleData(curMatchID)
    if totalscore !=None:
        if "rank" in totalscore["data"] and isinstance(totalscore["data"]["rank"],list):
            if len(totalscore["data"]["rank"]) > 0:
                for iteam in totalscore["data"]["rank"]:
                    player1=["-"]
                    player2=["-"]
                    player3=["-"]
                    score1 =["-",0,0] #本局分，是否第一，目前总分
                    score2 =["-",0,0]
                    score3 =["-",0,0]
                    score4 =["-",0,0]
                    score5 =["-",0,0]
                    score6 =["-",0,0]

                    # 从别处存的里面拿的
                    if len(m.singleMatchDatas)>=1 and m.singleMatchDatas[0]!=[]:
                        for index, itemhe in enumerate(m.singleMatchDatas[0]):
                            if itemhe["team_name"] == iteam["team_name"]:
                                score1 = [itemhe["score"],itemhe["isfirst"],float(itemhe["score"])]
                    if len(m.singleMatchDatas)>= 2 and m.singleMatchDatas[1]!=[]:
                        for index, itemhe in enumerate(m.singleMatchDatas[1]):
                            if itemhe["team_name"] == iteam["team_name"]:
                                score2 = [itemhe["score"],itemhe["isfirst"],float(itemhe["score"])+score1[2]]
                    if len(m.singleMatchDatas)>=3 and m.singleMatchDatas[2]!=[]:
                        for index, itemhe in enumerate(m.singleMatchDatas[2]):
                            if itemhe["team_name"] == iteam["team_name"]:
                                score3 = [itemhe["score"],itemhe["isfirst"],float(itemhe["score"])+score2[2]]
                    if len(m.singleMatchDatas)>=4 and m.singleMatchDatas[3]!=[]:
                        for index, itemhe in enumerate(m.singleMatchDatas[3]):
                            if itemhe["team_name"] == iteam["team_name"]:
                                score4 =[itemhe["score"],itemhe["isfirst"],float(itemhe["score"])+score3[2]]
                    if len(m.singleMatchDatas)>=5 and m.singleMatchDatas[4]!=[]:
                        for index, itemhe in enumerate(m.singleMatchDatas[4]):
                            if itemhe["team_name"] == iteam["team_name"]:
                                score5 = [itemhe["score"],itemhe["isfirst"],float(itemhe["score"])+score4[2]]
                    if len(m.singleMatchDatas)>=6 and m.singleMatchDatas[5]!=[]:
                        for index, itemhe in enumerate(m.singleMatchDatas[5]):
                            if itemhe["team_name"] == iteam["team_name"]:
                                score6 = [itemhe["score"],itemhe["isfirst"],float(itemhe["score"])+score5[2]]

                    #就这里接口返回的
                    if len(iteam["heros"]) >= 1:
                        player1 = [iteam["heros"][0]["role_name"]]
                    if len(iteam["heros"]) >= 2:
                        player2 = [iteam["heros"][1]["role_name"]]
                    if len(iteam["heros"]) >= 3:
                        player3 = [iteam["heros"][2]["role_name"]]
                    tmpteam = {
                        "rank":iteam["rank"],
                        "team_name":iteam["team_name"],
                        "players":[
                            {
                                "player_name": player1[0],
                            },
                            {
                                "player_name": player2[0],
                            },
                            {
                                "player_name": player3[0],
                            }
                        ],
                        "score1":score1[0],
                        "isfirst1":score1[1],
                        "isMatchPoint1": 1 if score1[2] >= m.matchPointScore else 0,
                        "score2":score2[0],
                        "isfirst2":score2[1],
                        "isMatchPoint2": 1 if score2[2] >= m.matchPointScore else 0,
                        "score3":score3[0],
                        "isfirst3":score3[1],
                        "isMatchPoint3": 1 if score3[2] >= m.matchPointScore else 0,
                        "score4":score4[0],
                        "isfirst4":score4[1],
                        "isMatchPoint4": 1 if score4[2] >= m.matchPointScore else 0,
                        "score5":score5[0],
                        "isfirst5":score5[1],
                        "isMatchPoint5": 1 if score5[2] >= m.matchPointScore else 0,
                        "score6":score6[0],
                        "isfirst6":score6[1],
                        "isMatchPoint6": 1 if score6[2] >= m.matchPointScore else 0,
                        "totalscore":iteam["team_score"]
                    }
                    teamlist.append(tmpteam)  #添加进来
    sortlist = sorted(teamlist, key=lambda x: x['rank'], reverse=False)
    # 更新 rank 字段
    # for rank, player in enumerate(sortlist):
    #     player['rank'] = rank + 1  # rank 从 1 开始      
    #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":sortlist,"matchPointScore":m.matchPointScore}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr

# 赛后战队数据，计算
def CapMatchEndData():
    global DEBUG
    scoredata = datasource.GetSingleData(m.curMatchID)
    if scoredata ==None:
        retjson = {"data":[]}
        jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
        return jsonstr
    teamlist = []  #队伍列表
    if scoredata != None:
        if "teams" in scoredata["data"] and isinstance(scoredata["data"]["teams"],list):
            if len(scoredata["data"]["teams"]) > 0:
                for iteam in scoredata["data"]["teams"]:
                    player1={"player_name":"-","hero":"-","skill1":"-","skill2":"-","kill_times":"-","cure":0,"damage":0,"assist_count":0,"total_live_time":0,"rescue_times":0}
                    player2={"player_name":"-","hero":"-","skill1":"-","skill2":"-","kill_times":"-","cure":0,"damage":0,"assist_count":0,"total_live_time":0,"rescue_times":0}
                    player3={"player_name":"-","hero":"-","skill1":"-","skill2":"-","kill_times":"-","cure":0,"damage":0,"assist_count":0,"total_live_time":0,"rescue_times":0}
                    if len(iteam["players"]) >= 1:
                        player1["player_name"] = iteam["players"][0]["player_game_name"]
                        player1["hero"] = m.convertList.get(str(iteam["players"][0]["hero_id"]),str(iteam["players"][0]["hero_id"]))
                        player1["skill1"] =  m.convertList.get(str(iteam["players"][0]["talent_skill_tid"][0]),str(iteam["players"][0]["talent_skill_tid"][0]))
                        player1["skill2"] = m.convertList.get(str(iteam["players"][0]["talent_skill_tid"][1]),str(iteam["players"][0]["talent_skill_tid"][1]))
                        player1["kill_times"] = iteam["players"][0]["kill_times"]
                        player1["cure"] = iteam["players"][0]["cure"]
                        player1["damage"] = iteam["players"][0]["damage"]
                        player1["assist_count"] = iteam["players"][0]["assist_count"]
                        player1["total_live_time"] = iteam["players"][0]["total_live_time"]
                        player1["rescue_times"] = iteam["players"][0]["rescue_times"]
                    if len(iteam["players"]) >= 2:
                        player2["player_name"] = iteam["players"][1]["player_game_name"]
                        player2["hero"] = m.convertList.get(str(iteam["players"][1]["hero_id"]),str(iteam["players"][1]["hero_id"]))
                        player2["skill1"] =  m.convertList.get(str(iteam["players"][1]["talent_skill_tid"][0]),str(iteam["players"][1]["talent_skill_tid"][0]))
                        player2["skill2"] = m.convertList.get(str(iteam["players"][1]["talent_skill_tid"][1]),str(iteam["players"][1]["talent_skill_tid"][1]))
                        player2["kill_times"] = iteam["players"][1]["kill_times"]
                        player2["cure"] = iteam["players"][1]["cure"]
                        player2["damage"] = iteam["players"][1]["damage"]
                        player2["assist_count"] = iteam["players"][1]["assist_count"]
                        player2["total_live_time"] = iteam["players"][1]["total_live_time"]
                        player2["rescue_times"] = iteam["players"][1]["rescue_times"]
                    if len(iteam["players"]) >= 3:
                        player3["player_name"] = iteam["players"][2]["player_game_name"]
                        player3["hero"] = m.convertList.get(str(iteam["players"][2]["hero_id"]),str(iteam["players"][2]["hero_id"]))
                        player3["skill1"] =  m.convertList.get(str(iteam["players"][2]["talent_skill_tid"][0]),str(iteam["players"][2]["talent_skill_tid"][0]))
                        player3["skill2"] = m.convertList.get(str(iteam["players"][2]["talent_skill_tid"][1]),str(iteam["players"][2]["talent_skill_tid"][1]))
                        player3["kill_times"] = iteam["players"][2]["kill_times"]
                        player3["cure"] = iteam["players"][2]["cure"]
                        player3["damage"] = iteam["players"][2]["damage"]
                        player3["assist_count"] = iteam["players"][2]["assist_count"]
                        player3["total_live_time"] = iteam["players"][2]["total_live_time"]
                        player3["rescue_times"] = iteam["players"][2]["rescue_times"]
                    tmpteam = {
                        "rank":iteam["rank"],
                        "team_name":iteam["team_name"],
                        "kill_score":iteam["kill_score"],
                        "rank_score":iteam["rank_score"],
                        "score":iteam["score"],
                        "players":[
                            player1,
                            player2,
                            player3
                        ],
                    }
                    teamlist.append(tmpteam)  #添加进来
    sortlist = sorted(teamlist, key=lambda x: x['rank'], reverse=False)
    # # 更新 rank 字段
    # for rank, player in enumerate(sortlist):
    #     player['rank'] = rank + 1  # rank 从 1 开始     
    #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":sortlist}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr

# 击杀榜前十数据，计算
def CapTop10():
    global DEBUG
    if DEBUG:
        print("打印一下singledatas\n")
        for ii in m.singleMatchDatas:
            print(ii)
    teamlist = []  #队伍列表
    #这个不需要调接口，直接从我存的里面算
    playerinfos = []
    for item in m.singleMatchDatas:
        for itemt in item:
            for itemp in itemt["players"]:
                flag = False
                for index, itemmy in enumerate(playerinfos):
                    if itemp["player_name"] == itemmy["player_name"]:
                        #有过这个人，加法
                        flag = True
                        itemmy["kill_times"]+=itemp["kill_times"]
                        itemmy["damage"]+=itemp["damage"]
                if not flag:
                    #没有过这个人，创建
                    tmp = {"team_name":itemt["team_name"],"player_name":itemp["player_name"],"kill_times":itemp["kill_times"],"damage":itemp["damage"],"rank":0}
                    playerinfos.append(tmp)
    #开始计算
    sorted_data = sorted(playerinfos, key=lambda x: (x['kill_times'], x['damage']), reverse=True)
    #sorted_data = sorted(playerinfos, key=lambda x: (x['kill_times'], -x['damage']))
    # 更新 rank 字段
    for rank, player in enumerate(sorted_data):
        player['rank'] = rank + 1  # rank 从 1 开始       
    #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":sorted_data[:10]}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr

# 场均分数据，计算
def CapAvgScore():
    global DEBUG
    teamlist = []  #队伍列表
    totalscore = datasource.GetRealtimeScore(m.curStageID,1)
    if totalscore ==None:
        retjson = {"data":[]}
        jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
        return jsonstr
    
    if totalscore != None:
        if "rank" in totalscore["data"] and isinstance(totalscore["data"]["rank"],list):
            if len(totalscore["data"]["rank"]) > 0:
                for iteam in totalscore["data"]["rank"]:
                    player1=["-"]
                    player2=["-"]
                    player3=["-"]
                    if iteam["heros"]!=None:
                        if len(iteam["heros"]) >= 1:
                            player1 = [iteam["heros"][0]["role_name"]]
                        if len(iteam["heros"]) >= 2:
                            player2 = [iteam["heros"][1]["role_name"]]
                        if len(iteam["heros"]) >= 3:
                            player3 = [iteam["heros"][2]["role_name"]]
                    tmpteam = {
                        "rank":iteam["rank"],
                        "score":iteam["team_score"],
                        "team_name":iteam["team_name"],
                        "players":[
                            {
                                "player_name": player1[0],
                            },
                            {
                                "player_name": player2[0],
                            },
                            {
                                "player_name": player3[0],
                            }
                        ],
                        "avgscore":iteam["team_score"]/(m.curMatchIndex+1)
                    }
                    
                    teamlist.append(tmpteam)  #添加进来
     #开始计算
    sorted_data = sorted(teamlist, key=lambda x: x['rank'], reverse=False)
    # # 更新 rank 字段
    # for rank, player in enumerate(sorted_data):
    #     player['rank'] = rank + 1  # rank 从 1 开始                       
    #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":sorted_data}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr

# 每局战果数据，计算
def CapAllMatchScore():
    global DEBUG
    teamlist = [{
        "Match":1,
        "team_name":"-",
        "score":"-",
        "players":[{"player_name":"-"},{"player_name":"-"},{"player_name":"-"}]
    },{
        "Match":2,
        "team_name":"-",
        "score":"-",
        "players":[{"player_name":"-"},{"player_name":"-"},{"player_name":"-"}]
    },{
        "Match":3,
        "team_name":"-",
        "score":"-",
        "players":[{"player_name":"-"},{"player_name":"-"},{"player_name":"-"}]
    },{
        "Match":4,
        "team_name":"-",
        "score":"-",
        "players":[{"player_name":"-"},{"player_name":"-"},{"player_name":"-"}]
    },{
        "Match":5,
        "team_name":"-",
        "score":"-",
        "players":[{"player_name":"-"},{"player_name":"-"},{"player_name":"-"}]
    },{
        "Match":6,
        "team_name":"-",
        "score":"-",
        "players":[{"player_name":"-"},{"player_name":"-"},{"player_name":"-"}]
    }]  #队伍列表
    
    if len(m.singleMatchDatas)>=1 and m.singleMatchDatas[0]!=[]:
        for index,item in enumerate(m.singleMatchDatas[0]):
            if item["srv_rank"] == 1:
                print("找到第一场")
                teamlist[0]["team_name"] = item["team_name"]
                teamlist[0]["score"] = item["score"]
                teamlist[0]["players"][0]["player_name"] = item["players"][0]["player_name"]
                teamlist[0]["players"][1]["player_name"] = item["players"][1]["player_name"]
                teamlist[0]["players"][2]["player_name"] = item["players"][2]["player_name"]
    if len(m.singleMatchDatas)>=2 and m.singleMatchDatas[1]!=[]:
        for index,item in enumerate(m.singleMatchDatas[1]):
            if item["srv_rank"] == 1:
                print("找到第二场")
                teamlist[1]["team_name"] = item["team_name"]
                teamlist[1]["score"] = item["score"]
                teamlist[1]["players"][0]["player_name"] = item["players"][0]["player_name"]
                teamlist[1]["players"][1]["player_name"] = item["players"][1]["player_name"]
                teamlist[1]["players"][2]["player_name"] = item["players"][2]["player_name"]
    if len(m.singleMatchDatas)>=3 and m.singleMatchDatas[2]!=[]:
        for index,item in enumerate(m.singleMatchDatas[2]):
            if item["srv_rank"] == 1:
                print("找到第三场")
                teamlist[2]["team_name"] = item["team_name"]
                teamlist[2]["score"] = item["score"]
                teamlist[2]["players"][0]["player_name"] = item["players"][0]["player_name"]
                teamlist[2]["players"][1]["player_name"] = item["players"][1]["player_name"]
                teamlist[2]["players"][2]["player_name"] = item["players"][2]["player_name"]
    if len(m.singleMatchDatas)>=4 and m.singleMatchDatas[3]!=[]:
        for index,item in enumerate(m.singleMatchDatas[3]):
            if item["srv_rank"] == 1:
                print("找到第四场")
                teamlist[3]["team_name"] = item["team_name"]
                teamlist[3]["score"] = item["score"]
                teamlist[3]["players"][0]["player_name"] = item["players"][0]["player_name"]
                teamlist[3]["players"][1]["player_name"] = item["players"][1]["player_name"]
                teamlist[3]["players"][2]["player_name"] = item["players"][2]["player_name"]
    if len(m.singleMatchDatas)>=5 and m.singleMatchDatas[4]!=[]:
        for index,item in enumerate(m.singleMatchDatas[4]):
            if item["srv_rank"] == 1:
                print("找到第五场")
                teamlist[4]["team_name"] = item["team_name"]
                teamlist[4]["score"] = item["score"]
                teamlist[4]["players"][0]["player_name"] = item["players"][0]["player_name"]
                teamlist[4]["players"][1]["player_name"] = item["players"][1]["player_name"]
                teamlist[4]["players"][2]["player_name"] = item["players"][2]["player_name"]
    if len(m.singleMatchDatas)>=6 and m.singleMatchDatas[5]!=[]:
        for index,item in enumerate(m.singleMatchDatas[5]):
            if item["srv_rank"] == 1:
                print("找到第六场")
                teamlist[5]["team_name"] = item["team_name"]
                teamlist[5]["score"] = item["score"]
                teamlist[5]["players"][0]["player_name"] = item["players"][0]["player_name"]
                teamlist[5]["players"][1]["player_name"] = item["players"][1]["player_name"]
                teamlist[5]["players"][2]["player_name"] = item["players"][2]["player_name"]
    #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":teamlist}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr

# 实时生存
def CapRealtimeLive():
    global DEBUG
    teamlist =[]
    realtimedata = datasource.GetRealtimeScore(m.curStageID, 0)
    if realtimedata ==None:
        retjson = {"data":[]}
        jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
        return jsonstr
    if realtimedata != None:
        if "rank" in realtimedata["data"] and isinstance(realtimedata["data"]["rank"],list):
            if len(realtimedata["data"]["rank"]) > 0:
                for iteam in realtimedata["data"]["rank"]:
                    tmpteam = {}
                    tmpteam["team_name"] = iteam["team_name"]
                    #1活 2死
                    tmpteam["players"] = [{"player_name":"-","player_state":2,"hero":"-"},{"player_name":"-","player_state":2,"hero":"-"},{"player_name":"-","player_state":2,"hero":"-"}]
                    tmpteam["team_state"] = 2
                    tmpteam["score"] = iteam["current_match_score"]  #应该都是本局的
                    tmpteam["total_score"] = iteam["team_score"]  #应该都是本局的
                    tmpteam["kill"] = iteam["kill_num"] #应该都是本局的
                    tmpteam["rank"] = 0
                    
                    if len(iteam["heros"]) >= 1:
                        tmpteam["players"][0]["player_state"] = iteam["heros"][0]["hero_state"]
                        tmpteam["players"][0]["player_name"] = iteam["heros"][0]["role_name"]
                        tmpteam["players"][0]["hero"] = m.convertList.get(str(iteam["heros"][0]["hero_id"]),str(iteam["heros"][0]["hero_id"]))
                    if len(iteam["heros"]) >= 2:
                        tmpteam["players"][1]["player_state"] = iteam["heros"][1]["hero_state"]
                        tmpteam["players"][1]["player_name"] = iteam["heros"][1]["role_name"]
                        tmpteam["players"][1]["hero"] = m.convertList.get(str(iteam["heros"][1]["hero_id"]),str(iteam["heros"][1]["hero_id"]))
                    if len(iteam["heros"]) >= 3:
                        tmpteam["players"][2]["player_state"] = iteam["heros"][2]["hero_state"]
                        tmpteam["players"][2]["player_name"] = iteam["heros"][2]["role_name"]
                        tmpteam["players"][2]["hero"] = m.convertList.get(str(iteam["heros"][2]["hero_id"]),str(iteam["heros"][2]["hero_id"]))

                    if tmpteam["players"][0]["player_state"]==1 or tmpteam["players"][1]["player_state"]==1 or tmpteam["players"][2]["player_state"]==1:
                        tmpteam["team_state"] = 1
                    else :
                        tmpteam["team_state"] = 2
                    teamlist.append(tmpteam)  

    #开始计算
    sorted_data = sorted(teamlist, key=lambda x: x['total_score'], reverse=True)
    # 更新 rank 字段
    forfindteam = {}
    for rank, team in enumerate(sorted_data):
        team['rank'] = rank + 1  # rank 从 1 开始  
        forfindteam[team["team_name"]] = rank+1
    for iteam in teamlist:
        iteam["rank"] = forfindteam.get(iteam["team_name"],0)

    #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":teamlist}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr


# 首杀
# 追击任务
# 叫阵任务
# 宝库开启
# 购买地煞
# 使用地煞
# 获得返魂
# 使用返魂
# 回阳镜开启
# 进入回阳
# 回阳结算
# 回阳选择buff
roomidforevent = {}
HYJ_save = {}
#实时触发们
def CapRealtimeEvent():
    global DEBUG
    global roomidforevent
    global HYJ_save
    teamlist = {}
    teamlist["ZJ_TeamA"] ="-"
    teamlist["ZJ_TeamB"] ="-"
    teamlist["disha_buy_player_name"] = "-"
    teamlist["disha_buy_item_name"] = "-"
    teamlist["disha_use_player_name"] = "-"
    teamlist["disha_use_item_name"] = "-"
    teamlist["baoku_buy_player_name"] = "-"
    teamlist["baoku_buy_item_name"] = "-"
    teamlist["baoku_use_player_name"] = "-"
    teamlist["baoku_use_item_name"] = "-"
    teamlist["fanhun_buy_player_name"] = "-"
    teamlist["fanhun_buy_item_name"] = "-"
    teamlist["fanhun_use_player_name"] = "-"
    teamlist["fanhun_use_item_name"] = "-"
    from datasource import TaskType
    # 追击
    zhuijiDatas = datasource.GetTask(TaskType.attacktask, m.curStageID)
    if zhuijiDatas ==None:
        retjson = {"data":[]}
        jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
        return jsonstr
    if zhuijiDatas != None:
        if zhuijiDatas["data"]!=None and zhuijiDatas["data"]["room_id"] not in roomidforevent:
            roomidforevent[zhuijiDatas["data"]["room_id"]] = {"buy_data":[],"use_data":[],"fanhun_buy":[],"fanhun_use":[],"pk1":{"team1a":None,"team1b":None,"team1as":None,"team1bs":None,"team2a":None,"team2b":None,"team2as":None,"team2bs":None,"team3a":None,"team3b":None,"team3as":None,"team3bs":None},"pk2":{"team1a":None,"team1b":None,"team1as":None,"team1bs":None,"team2a":None,"team2b":None,"team2as":None,"team2bs":None}}
            HYJ_save[zhuijiDatas["data"]["room_id"]] = {"HYJ_in":[],"HYJ_teamA":[],"HYJ_teamB":[],"HYJ_win":[],"HYJ_win_team":[]}
        if zhuijiDatas["data"]["data"]!=None and len(zhuijiDatas["data"]["data"])>0:
            if m.isSingle:
                teamlist["ZJ_TeamA"] = zhuijiDatas["data"]["data"][len(zhuijiDatas["data"]["data"])-1]["source_role_name"]
                teamlist["ZJ_TeamB"] = zhuijiDatas["data"]["data"][len(zhuijiDatas["data"]["data"])-1]["target_role_name"]
            else:
                teamlist["ZJ_TeamA"] = zhuijiDatas["data"]["data"][len(zhuijiDatas["data"]["data"])-1]["source_team_name"]
                teamlist["ZJ_TeamB"] = zhuijiDatas["data"]["data"][len(zhuijiDatas["data"]["data"])-1]["target_team_name"]

    # 宝库
    baokuDatas = datasource.GetTask(TaskType.baoku, m.curStageID)
    if baokuDatas != None:
        if baokuDatas["data"] !=None and baokuDatas["data"]["room_id"] not in roomidforevent:
            roomidforevent[baokuDatas["data"]["room_id"]] = {"buy_data":[],"use_data":[],"fanhun_buy":[],"fanhun_use":[],"pk1":{"team1a":None,"team1b":None,"team1as":None,"team1bs":None,"team2a":None,"team2b":None,"team2as":None,"team2bs":None,"team3a":None,"team3b":None,"team3as":None,"team3bs":None},"pk2":{"team1a":None,"team1b":None,"team1as":None,"team1bs":None,"team2a":None,"team2b":None,"team2as":None,"team2bs":None}}
            HYJ_save[baokuDatas["data"]["room_id"]] = {"HYJ_in":[],"HYJ_teamA":[],"HYJ_teamB":[],"HYJ_win":[],"HYJ_win_team":[]}
        if baokuDatas["data"]["buy_data"]!=None and len(baokuDatas["data"]["buy_data"])>0:
            #这个的含义，是最近一次购买
            newbuy = baokuDatas["data"]["buy_data"][len(baokuDatas["data"]["buy_data"])-1]
            teamlist["baoku_buy_player_name"] = newbuy["role_name"]
            teamlist["baoku_buy_item_name"] = newbuy["item_name"]
        if baokuDatas["data"]["use_data"]!=None and len(baokuDatas["data"]["use_data"])>0:
            #这个的含义，是最近一次购买
            newuse = baokuDatas["data"]["use_data"][len(baokuDatas["data"]["use_data"])-1]
            teamlist["baoku_use_player_name"] = newuse["role_name"]
            teamlist["baoku_use_player_name"] = newuse["item_name"]


    # 地煞
    dishaDatas = datasource.GetTask(TaskType.dishafu, m.curStageID)
    if dishaDatas != None:
        if dishaDatas["data"] !=None and dishaDatas["data"]["room_id"] not in roomidforevent:
            roomidforevent[dishaDatas["data"]["room_id"]] = {"buy_data":[],"use_data":[],"fanhun_buy":[],"fanhun_use":[],"pk1":{"team1a":None,"team1b":None,"team1as":None,"team1bs":None,"team2a":None,"team2b":None,"team2as":None,"team2bs":None,"team3a":None,"team3b":None,"team3as":None,"team3bs":None},"pk2":{"team1a":None,"team1b":None,"team1as":None,"team1bs":None,"team2a":None,"team2b":None,"team2as":None,"team2bs":None}}
            HYJ_save[dishaDatas["data"]["room_id"]] = {"HYJ_in":[],"HYJ_teamA":[],"HYJ_teamB":[],"HYJ_win":[],"HYJ_win_team":[]}
        if dishaDatas["data"]["buy_data"]!=None and len(dishaDatas["data"]["buy_data"])>0:
            #这个的含义，是最近一次购买
            newbuy = dishaDatas["data"]["buy_data"][len(dishaDatas["data"]["buy_data"])-1]
            teamlist["disha_buy_player_name"] = newbuy["role_name"]
            teamlist["disha_buy_item_name"] = newbuy["item_name"]
        if dishaDatas["data"]["use_data"]!=None and len(dishaDatas["data"]["use_data"])>0:
            #这个的含义，是最近一次购买
            newuse = dishaDatas["data"]["use_data"][len(dishaDatas["data"]["use_data"])-1]
            teamlist["disha_use_player_name"] = newuse["role_name"]
            teamlist["disha_use_item_name"] = newuse["item_name"]

    #返魂
    fanhunDatas = datasource.GetTask(TaskType.fanhunfu, m.curStageID)
    if fanhunDatas != None:
        if fanhunDatas["data"] !=None and fanhunDatas["data"]["room_id"] not in roomidforevent:
            roomidforevent[fanhunDatas["data"]["room_id"]] = {"buy_data":[],"use_data":[],"fanhun_buy":[],"fanhun_use":[],"pk1":{"team1a":None,"team1b":None,"team1as":None,"team1bs":None,"team2a":None,"team2b":None,"team2as":None,"team2bs":None,"team3a":None,"team3b":None,"team3as":None,"team3bs":None},"pk2":{"team1a":None,"team1b":None,"team1as":None,"team1bs":None,"team2a":None,"team2b":None,"team2as":None,"team2bs":None}}
            HYJ_save[fanhunDatas["data"]["room_id"]] = {"HYJ_in":[],"HYJ_teamA":[],"HYJ_teamB":[],"HYJ_win":[],"HYJ_win_team":[]}
        if fanhunDatas["data"]["buy_data"]!=None and len(fanhunDatas["data"]["buy_data"])>0:
            #这个的含义，是最近一次购买
            newbuy = fanhunDatas["data"]["buy_data"][len(fanhunDatas["data"]["buy_data"])-1]
            teamlist["fanhun_buy_player_name"] = newbuy["role_name"]
            teamlist["fanhun_buy_item_name"] = newbuy["item_name"]
        if fanhunDatas["data"]["use_data"] !=None and len(fanhunDatas["data"]["use_data"])>0:
            #这个的含义，是最近一次购买
            newuse = fanhunDatas["data"]["use_data"][len(fanhunDatas["data"]["use_data"])-1]
            teamlist["fanhun_use_player_name"] = newuse["role_name"]
            teamlist["fanhun_use_item_name"] = newuse["item_name"]
    
    #回阳
    huiyangDatas = datasource.GetTask(TaskType.leitai, m.curStageID)
    if huiyangDatas != None and huiyangDatas["data"] !=None and huiyangDatas["data"]["room_id"] not in roomidforevent:
        roomidforevent[huiyangDatas["data"]["room_id"]] = {"buy_data":[],"use_data":[],"fanhun_buy":[],"fanhun_use":[],"pk1":{"team1a":None,"team1b":None,"team1as":None,"team1bs":None,"team2a":None,"team2b":None,"team2as":None,"team2bs":None,"team3a":None,"team3b":None,"team3as":None,"team3bs":None},"pk2":{"team1a":None,"team1b":None,"team1as":None,"team1bs":None,"team2a":None,"team2b":None,"team2as":None,"team2bs":None}}
        HYJ_save[huiyangDatas["data"]["room_id"]] = {"HYJ_in":[],"HYJ_teamA":[],"HYJ_teamB":[],"HYJ_win":[],"HYJ_win_team":[]}
    nage = None
    if huiyangDatas != None:
        hyjpk1 = roomidforevent[huiyangDatas["data"]["room_id"]]["pk1"]
        hyjpk2 = roomidforevent[huiyangDatas["data"]["room_id"]]["pk2"]
        nage = HYJ_save[huiyangDatas["data"]["room_id"]]
    #nage 和下面这个长得一模一样
    # teamlist["HYJ_in"] =[]
    # teamlist["HYJ_teamA"] =[]
    # teamlist["HYJ_teamB"] = []
    # teamlist["HYJ_win"]=[]
    # teamlist["HYJ_win_team"] = []

    if huiyangDatas != None:
        # 第一局
        if huiyangDatas["data"]["data1"]["is_open"]!=None and huiyangDatas["data"]["data1"]["is_open"]==1:
            # 第一组
            if huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_a"]!=None or huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_b"]!=None:
                if huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_a"]!=hyjpk1["team1a"]: #or huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_b"]!=hyjpk1["team1b"]:
                    hyjpk1["team1a"] = huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_a"]
                    if len(nage["HYJ_in"]) == 0:
                        nage["HYJ_in"].append(1)
                        nage["HYJ_teamA"].append(hyjpk1["team1a"])
                        nage["HYJ_teamB"].append("-")
                        nage["HYJ_win"].append(0)
                        nage["HYJ_win_team"].append("-") 
                if huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_b"]!=hyjpk1["team1b"]:
                    hyjpk1["team1b"] = huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_b"]
                    nage["HYJ_in"][0]=1
                    nage["HYJ_teamB"][0] = hyjpk1["team1b"]
                if huiyangDatas["data"]["data1"]["pk_info"][0]["team_a_result"]!=None and huiyangDatas["data"]["data1"]["pk_info"][0]["team_a_result"]==1:
                    nage["HYJ_win"][0] = 1
                    nage["HYJ_win_team"][0] = huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_a"]
                if huiyangDatas["data"]["data1"]["pk_info"][0]["team_b_result"]!=None and huiyangDatas["data"]["data1"]["pk_info"][0]["team_b_result"]==1:
                    nage["HYJ_win"][0] = 1
                    nage["HYJ_win_team"][0] = huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_b"]

            # 第二组
            if huiyangDatas["data"]["data1"]["pk_info"][1]["team_name_a"]!=None or huiyangDatas["data"]["data1"]["pk_info"][1]["team_name_b"]!=None:
                if huiyangDatas["data"]["data1"]["pk_info"][1]["team_name_a"]!=hyjpk1["team2a"]: #or huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_b"]!=hyjpk1["team1b"]:
                    hyjpk1["team2a"] = huiyangDatas["data"]["data1"]["pk_info"][1]["team_name_a"]
                    if len(nage["HYJ_in"]) == 1:
                        nage["HYJ_in"][0] = 0

                        nage["HYJ_in"].append(1)
                        nage["HYJ_teamA"].append(hyjpk1["team2a"])
                        nage["HYJ_teamB"].append("-")
                        nage["HYJ_win"].append(0)
                        nage["HYJ_win_team"].append("-") 
                if huiyangDatas["data"]["data1"]["pk_info"][1]["team_name_b"]!=hyjpk1["team2b"]:
                    hyjpk1["team2b"] = huiyangDatas["data"]["data1"]["pk_info"][1]["team_name_b"]
                    nage["HYJ_in"][0]=0

                    nage["HYJ_in"][1]=1
                    nage["HYJ_teamB"][1] = hyjpk1["team2b"]
                if huiyangDatas["data"]["data1"]["pk_info"][1]["team_a_result"]!=None and huiyangDatas["data"]["data1"]["pk_info"][1]["team_a_result"]==1:
                    nage["HYJ_win"][0] = 0

                    nage["HYJ_win"][1] = 1
                    nage["HYJ_win_team"][1] = huiyangDatas["data"]["data1"]["pk_info"][1]["team_name_a"]
                if huiyangDatas["data"]["data1"]["pk_info"][1]["team_b_result"]!=None and huiyangDatas["data"]["data1"]["pk_info"][1]["team_b_result"]==1:
                    nage["HYJ_win"][0] = 0

                    nage["HYJ_win"][1] = 1
                    nage["HYJ_win_team"][1] = huiyangDatas["data"]["data1"]["pk_info"][1]["team_name_b"]

            # 第三组
            if huiyangDatas["data"]["data1"]["pk_info"][2]["team_name_a"]!=None or huiyangDatas["data"]["data1"]["pk_info"][2]["team_name_b"]!=None:
                if huiyangDatas["data"]["data1"]["pk_info"][2]["team_name_a"]!=hyjpk1["team3a"]: #or huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_b"]!=hyjpk1["team1b"]:
                    hyjpk1["team3a"] = huiyangDatas["data"]["data1"]["pk_info"][2]["team_name_a"]
                    if len(nage["HYJ_in"]) == 2:
                        nage["HYJ_in"][0] = 0
                        nage["HYJ_in"][1] = 0
                        
                        nage["HYJ_in"].append(1)
                        nage["HYJ_teamA"].append(hyjpk1["team3a"])
                        nage["HYJ_teamB"].append("-")
                        nage["HYJ_win"].append(0)
                        nage["HYJ_win_team"].append("-") 
                if huiyangDatas["data"]["data1"]["pk_info"][2]["team_name_b"]!=hyjpk1["team3b"]:
                    hyjpk1["team3b"] = huiyangDatas["data"]["data1"]["pk_info"][2]["team_name_b"]
                    nage["HYJ_in"][0] = 0
                    nage["HYJ_in"][1] = 0

                    nage["HYJ_in"][2]=1
                    nage["HYJ_teamB"][2] = hyjpk1["team3b"]
                if huiyangDatas["data"]["data1"]["pk_info"][2]["team_a_result"]!=None and huiyangDatas["data"]["data1"]["pk_info"][2]["team_a_result"]==1:
                    nage["HYJ_win"][0] = 0
                    nage["HYJ_win"][1] = 0

                    nage["HYJ_win"][2] = 1
                    nage["HYJ_win_team"][2] = huiyangDatas["data"]["data1"]["pk_info"][2]["team_name_a"]
                if huiyangDatas["data"]["data1"]["pk_info"][2]["team_b_result"]!=None and huiyangDatas["data"]["data1"]["pk_info"][2]["team_b_result"]==1:
                    nage["HYJ_win"][0] = 0
                    nage["HYJ_win"][1] = 0

                    nage["HYJ_win"][2] = 1
                    nage["HYJ_win_team"][2] = huiyangDatas["data"]["data1"]["pk_info"][2]["team_name_b"]

        # 第二局
        if huiyangDatas["data"]["data2"]["is_open"]!=None and huiyangDatas["data"]["data2"]["is_open"]==1:
            if len(nage["HYJ_in"])==0:
                #补三个
                nage["HYJ_in"].append(0)
                nage["HYJ_teamA"].append("-")
                nage["HYJ_teamB"].append("-")
                nage["HYJ_win"].append(0)
                nage["HYJ_win_team"].append("-") 
                nage["HYJ_in"].append(0)
                nage["HYJ_teamA"].append("-")
                nage["HYJ_teamB"].append("-")
                nage["HYJ_win"].append(0)
                nage["HYJ_win_team"].append("-") 
                nage["HYJ_in"].append(0)
                nage["HYJ_teamA"].append("-")
                nage["HYJ_teamB"].append("-")
                nage["HYJ_win"].append(0)
                nage["HYJ_win_team"].append("-") 
            elif len(nage["HYJ_in"])==1:
                #补两个
                nage["HYJ_in"].append(0)
                nage["HYJ_teamA"].append("-")
                nage["HYJ_teamB"].append("-")
                nage["HYJ_win"].append(0)
                nage["HYJ_win_team"].append("-") 
                nage["HYJ_in"].append(0)
                nage["HYJ_teamA"].append("-")
                nage["HYJ_teamB"].append("-")
                nage["HYJ_win"].append(0)
                nage["HYJ_win_team"].append("-") 
            elif len(nage["HYJ_in"])==2:
                #补一个
                nage["HYJ_in"].append(0)
                nage["HYJ_teamA"].append("-")
                nage["HYJ_teamB"].append("-")
                nage["HYJ_win"].append(0)
                nage["HYJ_win_team"].append("-") 
            # 第一组 4
            if huiyangDatas["data"]["data2"]["pk_info"][0]["team_name_a"]!=None or huiyangDatas["data"]["data2"]["pk_info"][0]["team_name_b"]!=None:
                if huiyangDatas["data"]["data2"]["pk_info"][0]["team_name_a"]!=hyjpk2["team1a"]: #or huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_b"]!=hyjpk1["team1b"]:
                    hyjpk2["team1a"] = huiyangDatas["data"]["data2"]["pk_info"][0]["team_name_a"]
                    if len(nage["HYJ_in"]) == 3:
                        nage["HYJ_in"][0] = 0
                        nage["HYJ_in"][1] = 0
                        nage["HYJ_in"][2] = 0

                        nage["HYJ_in"].append(1)
                        nage["HYJ_teamA"].append(hyjpk2["team1a"])
                        nage["HYJ_teamB"].append("-")
                        nage["HYJ_win"].append(0)
                        nage["HYJ_win_team"].append("-") 
                if huiyangDatas["data"]["data2"]["pk_info"][0]["team_name_b"]!=hyjpk2["team1b"]:
                    hyjpk2["team1b"] = huiyangDatas["data"]["data2"]["pk_info"][0]["team_name_b"]
                    nage["HYJ_in"][0] = 0
                    nage["HYJ_in"][1] = 0
                    nage["HYJ_in"][2] = 0
                    
                    nage["HYJ_in"][3]=1
                    nage["HYJ_teamB"][3] = hyjpk2["team1b"]
                if huiyangDatas["data"]["data2"]["pk_info"][0]["team_a_result"]!=None and huiyangDatas["data"]["data2"]["pk_info"][0]["team_a_result"]==1:
                    nage["HYJ_win"][0] = 0
                    nage["HYJ_win"][1] = 0
                    nage["HYJ_win"][2] = 0

                    nage["HYJ_win"][3] = 1
                    nage["HYJ_win_team"][3] = huiyangDatas["data"]["data2"]["pk_info"][0]["team_name_a"]
                if huiyangDatas["data"]["data2"]["pk_info"][0]["team_b_result"]!=None and huiyangDatas["data"]["data2"]["pk_info"][0]["team_b_result"]==1:
                    nage["HYJ_win"][0] = 0
                    nage["HYJ_win"][1] = 0
                    nage["HYJ_win"][2] = 0

                    nage["HYJ_win"][3] = 1
                    nage["HYJ_win_team"][3] = huiyangDatas["data"]["data2"]["pk_info"][0]["team_name_b"]

            # 第二组
            if huiyangDatas["data"]["data2"]["pk_info"][1]["team_name_a"]!=None or huiyangDatas["data"]["data2"]["pk_info"][1]["team_name_b"]!=None:
                if huiyangDatas["data"]["data2"]["pk_info"][1]["team_name_a"]!=hyjpk2["team2a"]: #or huiyangDatas["data"]["data1"]["pk_info"][0]["team_name_b"]!=hyjpk1["team1b"]:
                    hyjpk2["team2a"] = huiyangDatas["data"]["data2"]["pk_info"][1]["team_name_a"]
                    if len(nage["HYJ_in"]) == 4:
                        nage["HYJ_in"][0] = 0
                        nage["HYJ_in"][1] = 0
                        nage["HYJ_in"][2] = 0
                        nage["HYJ_in"][3] = 0

                        nage["HYJ_in"].append(1)
                        nage["HYJ_teamA"].append(hyjpk2["team2a"])
                        nage["HYJ_teamB"].append("-")
                        nage["HYJ_win"].append(0)
                        nage["HYJ_win_team"].append("-") 
                if huiyangDatas["data"]["data2"]["pk_info"][1]["team_name_b"]!=hyjpk2["team2b"]:
                    hyjpk2["team2b"] = huiyangDatas["data"]["data2"]["pk_info"][1]["team_name_b"]
                    nage["HYJ_in"][0] = 0
                    nage["HYJ_in"][1] = 0
                    nage["HYJ_in"][2] = 0
                    nage["HYJ_in"][3] = 0
                    
                    nage["HYJ_in"][4]=1
                    nage["HYJ_teamB"][4] = hyjpk2["team2b"]
                if huiyangDatas["data"]["data2"]["pk_info"][1]["team_a_result"]!=None and huiyangDatas["data"]["data2"]["pk_info"][1]["team_a_result"]==1:
                    nage["HYJ_win"][0] = 0
                    nage["HYJ_win"][1] = 0
                    nage["HYJ_win"][2] = 0
                    nage["HYJ_win"][3] = 0

                    nage["HYJ_win"][4] = 1
                    nage["HYJ_win_team"][4] = huiyangDatas["data"]["data2"]["pk_info"][1]["team_name_a"]
                if huiyangDatas["data"]["data2"]["pk_info"][1]["team_b_result"]!=None and huiyangDatas["data"]["data2"]["pk_info"][1]["team_b_result"]==1:
                    nage["HYJ_win"][0] = 0
                    nage["HYJ_win"][1] = 0
                    nage["HYJ_win"][2] = 0
                    nage["HYJ_win"][3] = 0

                    nage["HYJ_win"][4] = 1
                    nage["HYJ_win_team"][4] = huiyangDatas["data"]["data2"]["pk_info"][1]["team_name_b"]
    # 这是列表型式的，他们不要
    # for i in nage["HYJ_in"]:
    #     teamlist["HYJ_in"].append(i)
    # for i in nage["HYJ_teamA"]:
    #     teamlist["HYJ_teamA"].append(i)
    # for i in nage["HYJ_teamB"]:
    #     teamlist["HYJ_teamB"].append(i)
    # for i in nage["HYJ_win"]:
    #     teamlist["HYJ_win"].append(i)
    # for i in nage["HYJ_win_team"]:
    #     teamlist["HYJ_win_team"].append(i)

    # 换成固定型式的，麻烦的一
    teamlist["HYJ_in_1"] =0
    teamlist["HYJ_teamA_1"] = "-"
    teamlist["HYJ_teamB_1"] = "-"
    teamlist["HYJ_win_1"] = 0
    teamlist["HYJ_win_team_1"] = "-"

    teamlist["HYJ_in_2"] =0
    teamlist["HYJ_teamA_2"] = "-"
    teamlist["HYJ_teamB_2"] = "-"
    teamlist["HYJ_win_2"] = 0
    teamlist["HYJ_win_team_2"] = "-"

    teamlist["HYJ_in_3"] =0
    teamlist["HYJ_teamA_3"] = "-"
    teamlist["HYJ_teamB_3"] = "-"
    teamlist["HYJ_win_3"] = 0
    teamlist["HYJ_win_team_3"] = "-"

    teamlist["HYJ_in_4"] =0
    teamlist["HYJ_teamA_4"] = "-"
    teamlist["HYJ_teamB_4"] = "-"
    teamlist["HYJ_win_4"] = 0
    teamlist["HYJ_win_team_4"] = "-"

    teamlist["HYJ_in_5"] =0
    teamlist["HYJ_teamA_5"] = "-"
    teamlist["HYJ_teamB_5"] = "-"
    teamlist["HYJ_win_5"] = 0
    teamlist["HYJ_win_team_5"] = "-"

    if nage !=None:
        if len(nage["HYJ_in"]) > 0:
            teamlist["HYJ_in_1"] =nage["HYJ_in"][0]
            teamlist["HYJ_teamA_1"] =nage["HYJ_teamA"][0]
            teamlist["HYJ_teamB_1"] =nage["HYJ_teamB"][0]
            teamlist["HYJ_win_1"] =nage["HYJ_win"][0]
            teamlist["HYJ_win_team_1"] =nage["HYJ_win_team"][0]
        if len(nage["HYJ_in"]) > 1:
            teamlist["HYJ_in_2"] =nage["HYJ_in"][1]
            teamlist["HYJ_teamA_2"] =nage["HYJ_teamA"][1]
            teamlist["HYJ_teamB_2"] =nage["HYJ_teamB"][1]
            teamlist["HYJ_win_2"] =nage["HYJ_win"][1]
            teamlist["HYJ_win_team_2"] =nage["HYJ_win_team"][1]
        if len(nage["HYJ_in"]) > 2:
            teamlist["HYJ_in_3"] =nage["HYJ_in"][2]
            teamlist["HYJ_teamA_3"] =nage["HYJ_teamA"][2]
            teamlist["HYJ_teamB_3"] =nage["HYJ_teamB"][2]
            teamlist["HYJ_win_3"] =nage["HYJ_win"][2]
            teamlist["HYJ_win_team_3"] =nage["HYJ_win_team"][2]
        if len(nage["HYJ_in"]) > 3:
            teamlist["HYJ_in_4"] =nage["HYJ_in"][3]
            teamlist["HYJ_teamA_4"] =nage["HYJ_teamA"][3]
            teamlist["HYJ_teamB_4"] =nage["HYJ_teamB"][3]
            teamlist["HYJ_win_4"] =nage["HYJ_win"][3]
            teamlist["HYJ_win_team_4"] =nage["HYJ_win_team"][3]
        if len(nage["HYJ_in"]) > 4:
            teamlist["HYJ_in_5"] =nage["HYJ_in"][4]
            teamlist["HYJ_teamA_5"] =nage["HYJ_teamA"][4]
            teamlist["HYJ_teamB_5"] =nage["HYJ_teamB"][4]
            teamlist["HYJ_win_5"] =nage["HYJ_win"][4]
            teamlist["HYJ_win_team_5"] =nage["HYJ_win_team"][4]

    # #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":teamlist}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr

def CapMvp():
    global DEBUG
    teamlist = {}
    # get singleMatch
    datas = datasource.GetSingleData(m.curMatchID)
    if datas ==None:
        retjson = {"data":[]}
        jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
        return jsonstr
    mvpplayer = {}
    # 首先找到那个mvp
    if datas!=None:
        if datas["data"]!=None and "teams" in datas["data"] and isinstance(datas["data"]["teams"],list):
            if len(datas["data"]["teams"]) > 0:
                maxdamage = 0
                maxkills = 0
                maxMelee_damage = 0
                maxcounterstrikes = 0
                maxcure = 0
                maxkill_in_reborn_period= 0
                maxassist_count = 0
                maxrescue_times = 0
                for index,item in enumerate(datas["data"]["teams"]):
                    if item["rank"] == 1:
                        mkills = 0
                        for everykill in item["players"]:
                            if everykill["kill_times"]>mkills:
                                mkills = everykill["kill_times"]
                                mvpplayer["team_name"] = item["team_name"]
                                mvpplayer["kill_times"] = everykill["kill_times"]
                                mvpplayer["player_name"] = everykill["player_game_name"]
                                mvpplayer["damage"] = everykill["damage"]
                                mvpplayer["melee_damage"] = everykill["melee_damage"]
                                mvpplayer["counterstrikes"] = everykill["shock_count"]
                                mvpplayer["kill_in_reborn_period"] = everykill["kill_in_reborn_period"]
                                mvpplayer["cure"] = everykill["cure"]
                                mvpplayer["assist_count"] = everykill["assist_count"]
                                mvpplayer["rescue_times"] = everykill["rescue_times"]

                                if everykill["weapon_with_damage_3"]==None:
                                    weap1 = ["-","-"]
                                    weap2 = ["-","-"]
                                    weap3 = ["-","-"]   
                                else:
                                    if len(everykill["weapon_with_damage_3"])>0:
                                        weap1 = str(everykill["weapon_with_damage_3"][0]).split(", ")
                                    else:
                                        weap1 = ["-","-"]
                                    if len(everykill["weapon_with_damage_3"])>1:    
                                        weap2 = str(everykill["weapon_with_damage_3"][1]).split(", ")
                                    else:
                                        weap2 = ["-","-"]
                                    if len(everykill["weapon_with_damage_3"])>2: 
                                        weap3 = str(everykill["weapon_with_damage_3"][2]).split(", ")
                                    else:
                                        weap3 = ["-","-"]   
                                mvpplayer["weapon1"] = weap1[0]
                                mvpplayer["weapon1_damage"] = weap1[1]
                                mvpplayer["weapon2"] = weap2[0]
                                mvpplayer["weapon2_damage"] = weap2[1]
                                mvpplayer["weapon3"] = weap3[0]
                                mvpplayer["weapon3_damage"] = weap3[1]

                                if everykill["soul_items_tids"] == None:
                                    mvpplayer["skill1"] = "-"
                                    mvpplayer["skill2"] = "-"
                                else:
                                    if len(everykill["talent_skill_tid"]) >0:
                                        mvpplayer["skill1"] = m.convertList.get(str(everykill["talent_skill_tid"][0]),str(everykill["talent_skill_tid"][0]))
                                    else:
                                        mvpplayer["skill1"] = "-"
                                    if len(everykill["talent_skill_tid"]) >1:    
                                        mvpplayer["skill2"] = m.convertList.get(str(everykill["talent_skill_tid"][1]),str(everykill["talent_skill_tid"][1])) 
                                    else:
                                        mvpplayer["skill2"] = "-"

                                if everykill["soul_items_tids"] == None:
                                     mvpplayer["soul1"] = "-"
                                     mvpplayer["soul2"] = "-"
                                     mvpplayer["soul3"] = "-"
                                     mvpplayer["soul4"] = "-"
                                     mvpplayer["soul5"] = "-"
                                     mvpplayer["soul6"] = "-"
                                else:
                                    if len(everykill["soul_items_tids"]) > 0:
                                        mvpplayer["soul1"] = m.convertList.get(str(everykill["soul_items_tids"][0]),str(everykill["soul_items_tids"][0])).replace("•","·") 
                                    else:
                                        mvpplayer["soul1"] = "-"
                                    if len(everykill["soul_items_tids"]) > 1:
                                        mvpplayer["soul2"] = m.convertList.get(str(everykill["soul_items_tids"][1]),str(everykill["soul_items_tids"][1])).replace("•","·") 
                                    else:
                                        mvpplayer["soul2"] = "-"
                                    if len(everykill["soul_items_tids"]) > 2:
                                        mvpplayer["soul3"] = m.convertList.get(str(everykill["soul_items_tids"][2]),str(everykill["soul_items_tids"][2])).replace("•","·") 
                                    else:
                                        mvpplayer["soul3"] = "-"
                                    if len(everykill["soul_items_tids"]) > 3:
                                        mvpplayer["soul4"] = m.convertList.get(str(everykill["soul_items_tids"][3]),str(everykill["soul_items_tids"][3])).replace("•","·") 
                                    else:
                                        mvpplayer["soul4"] = "-"
                                    if len(everykill["soul_items_tids"]) > 4:
                                        mvpplayer["soul5"] = m.convertList.get(str(everykill["soul_items_tids"][4]),str(everykill["soul_items_tids"][4])).replace("•","·") 
                                    else:
                                        mvpplayer["soul5"] = "-"
                                    if len(everykill["soul_items_tids"]) > 5:    
                                        mvpplayer["soul6"] = m.convertList.get(str(everykill["soul_items_tids"][5]),str(everykill["soul_items_tids"][5])).replace("•","·") 
                                    else:
                                        mvpplayer["soul6"] = "-"
                                mvpplayer["hero"] = m.convertList.get(str(everykill["hero_id"]),str(everykill["hero_id"])) 
                #好，接下来算最高值
                for index,item in enumerate(datas["data"]["teams"]):
                    for everyone in item["players"]:
                        if everyone["kill_times"] > maxkills:
                            maxkills = everyone["kill_times"]
                        if everyone["damage"] > maxdamage:
                            maxdamage = everyone["damage"]
                        if everyone["cure"] > maxcure:
                            maxcure = everyone["cure"]
                        if everyone["kill_in_reborn_period"] > maxkill_in_reborn_period:
                            maxkill_in_reborn_period = everyone["kill_in_reborn_period"]
                        if everyone["assist_count"] > maxassist_count:
                            maxassist_count = everyone["assist_count"]
                        if everyone["rescue_times"] > maxrescue_times:
                            maxrescue_times = everyone["rescue_times"]
                        if everyone["melee_damage"] > maxMelee_damage:
                            maxMelee_damage = everyone["melee_damage"]
                        if everyone["shock_count"] > maxcounterstrikes:
                            maxcounterstrikes = everyone["shock_count"]
                mvpplayer["max_damage"] = maxdamage
                mvpplayer["max_kill_times"] = maxkills
                mvpplayer["max_kill_in_reborn_period"] = maxkill_in_reborn_period
                mvpplayer["max_assist_count"] = maxassist_count
                mvpplayer["max_rescue_times"] = maxrescue_times
                mvpplayer["max_cure"] = maxcure
                mvpplayer["max_melee_damage"] = maxMelee_damage
                mvpplayer["max_counterstrikes"] = maxcounterstrikes
    #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":mvpplayer}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr        

def CapOuterWeb():
    global DEBUG
    teamlist = {}
    # get singleMatch
    datas = datasource.GetOuterWeb(m.curUUID)
    #好，填充完了终于是，转成json字符串返回回去吧
    retjson = {"data":datas}
    jsonstr = json.dumps(retjson, ensure_ascii=False, indent=4)
    if DEBUG:
        print("我算完的是:\n"+jsonstr)
    return jsonstr        

def thd2RefreshStage():
    m.RefreshStages()
    while True:
        time.sleep(5)
        m.RefreshStagesNew()

if __name__ == "__main__":
    mt = threading.Thread(target=thd2RefreshStage)
    mt.start()
    runapp()
    #mt.join()
    #CapHeroSelectTeam()


#他们要的13个接口

# 1 英雄选择3排
# 战队名
# 选手名*3
# 选择英雄*3
# 携带技能f*3
# 携带技能v*3
# 阵容选择率
# 场均得分
# 上局积分
# 地图名 -
# 天气 -

# 2 英雄选择单排
# 战队名
# 选手名
# 选择英雄
# 携带技能f
# 携带技能v
# 英雄选择率
# 场均得分
# 上局积分
# 地图名 -
# 天气 -

# 3 跳点展示
# 战队/选手跳点坐标

# 4 单局积分
# 排名
# 战队名/选手名
# 击杀数
# 击败分
# 排名分
# 单局总分

# 5 总积分
# 排名
# 战队名/选手名
# 第123456场积分
# 第123456场吃鸡判定
# 总积分

# 6 赛后战队数据
# 排名
# 战队名称
# 选手名*3
# 本局英雄*3
# F*3
# V*3
# 击败数*3
# 治疗量*3
# 伤害*3
# 助攻数*3
# 存活时间*3
# 救援次数*3

# 7 mvp三排
# 战队名
# 选手名
# 击败树
# 伤害量
# 治疗量
# 返魂期击杀
# 助攻
# 战神数
# 伤害最高武器and伤害1
# 伤害最高武器and伤害2
# 伤害最高武器and伤害3
# 使用魂玉*6
# 使用英雄
# F
# V

# 8 mvp单排
# 选手名
# 击败树
# 伤害量
# 治疗量
# 近战伤害
# 振捣数
# 战神数
# 伤害最高武器and伤害1
# 伤害最高武器and伤害2
# 伤害最高武器and伤害3
# 使用魂玉*6
# 使用英雄
# F
# V

# 9 三排击杀榜
# 战队名*10
# 选手名*10
# 排名*10
# 总击杀10
# 总伤害10

# 10 单排击杀
# 选手名*10
# 排名*10
# 总击杀10
# 总伤害10

# 11 场均得分
# 战队名/选手名 *16
# 场均得分*16

# 12 实时生存 三排
# 战队名
# 英雄名*3
# 存活状态 正常返魂死亡
# 全队状态  在不在
# 总击败
# 当前总分

# 13 单排的实时生存
# 选手名
# 英雄名
# 存活状态
# 总击败
# 当前总分

# 14 触发事件
# 首杀
# 追击任务
# 叫阵任务
# 宝库开启
# 购买地煞
# 使用地煞
# 获得返魂
# 使用返魂
# 回阳镜开启
# 进入回阳
# 回阳结算
# 回阳选择buff

# 15 每局赛果
# 吃鸡队伍名 选手名 *6
# 本局得分
# 地图名 -
# 天气 -